<template>
  <div class="home-container">
    <!-- 页面顶部标题栏 -->
    <div class="header-section">
      <div class="header-left">
        <el-icon class="logo-icon"><Coffee /></el-icon>
        <h1 class="system-title">奶茶培训系统</h1>
      </div>
      <div class="header-right">
        <div class="user-info" v-if="authStore.username">
          <el-icon class="user-icon"><User /></el-icon>
          <span class="username">{{ authStore.username }}</span>
        </div>
        <el-button
            type="text"
            class="logout-btn"
            @click="handleLogout"
            :loading="logoutLoading"
        >
          <el-icon><Logout /></el-icon> 退出登录
        </el-button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧菜单栏 -->
      <div class="menu-sidebar">
        <!-- 加载状态显示 -->
        <div v-if="loading" class="loading-container">
          <el-spinner size="medium" class="menu-spinner" />
          <span class="loading-text">正在加载菜单...</span>
        </div>

        <!-- 错误状态显示 -->
        <div v-else-if="error" class="error-container">
          <div class="error-card">
            <el-alert
                title="菜单加载失败"
                description="{{ error }}"
                type="error"
                show-icon
                class="error-alert"
            />
            <el-button
                type="primary"
                size="small"
                @click="reloadMenus"
                class="reload-btn"
                :loading="reloading"
            >
              <el-icon><RefreshLeft /></el-icon> 重新加载
            </el-button>
          </div>
        </div>

        <!-- 菜单渲染 -->
        <el-menu
            v-else
            :router="true"
            :unique-opened="true"
            mode="vertical"
            class="custom-menu"
            :default-active="activeMenu"
            background-color="#fff9f0"
            text-color="#8c603e"
            active-text-color="#e67e22"
            :collapse-transition="false"
        >
          <!-- 欢迎信息 -->
          <div class="welcome-message">
            <p class="welcome-text">欢迎回来</p>
            <p class="welcome-subtitle">开始您的培训之旅</p>
          </div>

          <!-- 菜单列表 -->
          <menu-tree v-for="menu in useAuthStore().myMenus" :menu="menu"></menu-tree>
        </el-menu>
      </div>

      <!-- 右侧内容区域 - 优化布局 -->
      <div class="content-area">
        <div class="content-wrapper">
          <router-view />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import MenuTree from "@/components/menuTree/MenuTree.vue";
import {useAuthStore} from "@/stores/auth.ts";
import {onMounted, ref, computed} from "vue";
import {useRoute, useRouter} from 'vue-router';
import {Coffee, User, RefreshLeft} from '@element-plus/icons-vue';
import {ElMessage} from 'element-plus';

const authStore = useAuthStore();
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const error = ref('');
const reloading = ref(false);
const logoutLoading = ref(false);

// 使用计算属性获取菜单数据
const menus = computed(() => {
  return authStore.myMenus || [];
});

// 获取当前活动菜单
const activeMenu = computed(() => {
  return route.path || '';
});

// 重新加载菜单的方法
const reloadMenus = async () => {
  reloading.value = true;
  error.value = '';
  try {
    // 这里可以添加重新加载菜单的逻辑
    // 例如调用authStore中的方法重新获取菜单
    console.log('Reloading menus...');
    // 模拟加载延迟
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 如果需要从API重新获取菜单，可以调用类似如下方法
    // await authStore.loadMenus();

    if (!authStore.myMenus || authStore.myMenus.length === 0) {
      error.value = '暂无可用菜单，请联系管理员';
    }
  } catch (err) {
    error.value = '菜单重新加载失败，请稍后再试';
    console.error('Reload menus error:', err);
  } finally {
    reloading.value = false;
  }
};

// 退出登录处理
const handleLogout = async () => {
  logoutLoading.value = true;
  try {
    // 先调用 logout 方法
    await authStore.logout();

    // 添加短暂延迟确保状态完全清除
    await new Promise(resolve => setTimeout(resolve, 300));

    ElMessage.success('退出登录成功');

    // 强制清除所有可能的缓存并跳转
    // window.location.href = '/login';
    // router.push('/login');
    // 添加这行作为后备方案
    // window.location.reload();
  } catch (error) {
    ElMessage.error('退出登录失败，请稍后重试');
    console.error('Logout error:', error);
  } finally {
    logoutLoading.value = false;
  }
};

// 组件挂载时检查菜单数据
onMounted(() => {
  if (!authStore.myMenus || authStore.myMenus.length === 0) {
    console.log('No menus available, showing empty state');
    // 可以考虑自动触发重新加载
    // reloadMenus();
  }
});
</script>

<style scoped>
/* 主容器样式 */
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #fff5e6 0%, #fff0d9 100%);
  display: flex;
  flex-direction: column;
}

/* 顶部标题栏样式 */
.header-section {
  background: white;
  box-shadow: 0 2px 8px rgba(230, 126, 34, 0.1);
  padding: 0 24px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-icon {
  font-size: 24px;
  color: #e67e22;
}

.system-title {
  font-size: 20px;
  color: #e67e22;
  font-weight: 600;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #8c603e;
}

.user-icon {
  font-size: 16px;
}

.username {
  font-size: 14px;
}

.logout-btn {
  color: #e67e22;
  font-size: 14px;
}

.logout-btn:hover {
  background-color: #fff0d9;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  display: flex;
  gap: 0;
  margin-top: 16px;
  padding: 0 16px 16px;
  min-height: calc(100vh - 88px);
}

/* 左侧菜单边栏样式 - 添加滚动支持 */
.menu-sidebar {
  width: 260px;
  height: calc(100vh - 88px);
  border-radius: 12px;
  overflow-y: auto; /* 改为垂直滚动 */
  box-shadow: 0 4px 12px rgba(230, 126, 34, 0.1);
  background: white;
  position: sticky;
  top: 80px;
}

/* 自定义滚动条样式 - 左侧菜单 */
.menu-sidebar::-webkit-scrollbar {
  width: 6px;
}
.menu-sidebar::-webkit-scrollbar-track {
  background: #fff5e6;
  border-radius: 3px;
}

.menu-sidebar::-webkit-scrollbar-thumb {
  background: #ffcc99;
  border-radius: 3px;
}

.menu-sidebar::-webkit-scrollbar-thumb:hover {
  background: #ffb366;
}



/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #e67e22;
  gap: 12px;
}

.menu-spinner {
  color: #e67e22;
}

.loading-text {
  font-size: 14px;
  color: #8c603e;
}

/* 错误状态样式 */
.error-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 24px;
}

.error-card {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
  padding: 20px;
  background: #fff8f0;
  border-radius: 8px;
  border: 1px solid #ffd699;
}

.error-alert {
  width: 100%;
}

.reload-btn {
  background: #e67e22;
  border-color: #e67e22;
}

.reload-btn:hover {
  background: #d35400;
  border-color: #d35400;
}

/* 自定义菜单样式 */
.custom-menu {
  height: 100%;
  border-right: none;
  background: white;
}

/* 欢迎信息样式 */
.welcome-message {
  padding: 24px;
  text-align: center;
  border-bottom: 1px solid #ffe8cc;
  background: linear-gradient(135deg, #fff9f0 0%, #fff5e6 100%);
}

.welcome-text {
  font-size: 16px;
  font-weight: 600;
  color: #e67e22;
  margin: 0 0 4px 0;
}

.welcome-subtitle {
  font-size: 12px;
  color: #8c603e;
  margin: 0;
}

/* 右侧内容区域样式 - 添加滚动支持 */
.content-area {
  flex: 1;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(230, 126, 34, 0.1);
  margin-left: 16px;
  min-height: calc(100vh - 88px);
  display: flex;
  flex-direction: column;
  overflow-y: auto; /* 添加垂直滚动 */
}

/* 自定义滚动条样式 - 右侧内容 */
.content-area::-webkit-scrollbar {
  width: 8px;
}

.content-area::-webkit-scrollbar-track {
  background: #f8f8f8;
  border-radius: 4px;
}

.content-area::-webkit-scrollbar-thumb {
  background: #e0e0e0;
  border-radius: 4px;
}

.content-area::-webkit-scrollbar-thumb:hover {
  background: #d0d0d0;
}


/* 内容包装器 - 确保router-view完全填充 */
.content-wrapper {
  flex: 1;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 确保router-view填充整个内容区域 */
:deep(.router-view) {
  flex: 1;
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .menu-sidebar {
    width: 240px;
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }

  .menu-sidebar {
    width: 100%;
    height: auto;
    position: static;
  }

  .content-area {
    margin-left: 0;
    margin-top: 16px;
  }

  .header-section {
    padding: 0 16px;
  }

  .system-title {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .header-right {
    gap: 12px;
  }

  .username {
    display: none;
  }
}
</style>
